/**
 * Created by 16020025 on 2017/5/2.
 */
//判断用户状态
function judgeUserState(uid, callback){
    $.ajax({
        url : "judge-user-state",
        type: "POST",
        data : {id : uid},
        dataType : "json",
        async : false,
        success: function(data) {
            var result = data.rs;
            if("Y" === result){
                if(callback){
                    callback();
                }
            } else {
                $.toast(result);
                return false;
            }
        },
        error: function(){
            $.toast("系统繁忙，请稍后再试");
            return false;
        }
    });
}
function getIneract() {
    $(".main-header").html('<h1 class="title">圈圈</h1><i class="pull-right icon icon-publish" onclick="openInteractPopup(\'mem\')"></i>');
    $(".main-header").show();
    $(".main-content").css("top", "2.2rem");
    clearFilter();
    $.showIndicator();
    $.ajax({
        type: "POST",
        url: "yp-ws-app-getInteract",
        data: {},
        dataType: "json",
        success: function(data) {
            $("#pics").val("");
            $.hideIndicator();
            if (data.rs == "Y") {
                var tpl = document.getElementById('interactTpl').innerHTML;
                var html = template(tpl, {
                    "data": data.data
                });
                $('#interactDiv').html(html);
            } else {
                $.toast(data.rs);
            }
        },
        error: function(data) {
            $.hideIndicator();
            $.toast("网络出错");
        }
    });

}

function showSelectContacts(type, func, fk_gym_id, level) {
    $.showIndicator();
    $.ajax({
        type: "POST",
        url: "yp-ws-app-concacts",
        data: {
            type: type,
            level: level
        },
        dataType: "json",
        success: function(data) {
            $.hideIndicator();
            if (data.hasOwnProperty("rs") && data.rs == "Y") {
                $.popup('.popup-concacts');
                var tpl = document.getElementById('popconcactsTpl').innerHTML;
                var html = template(tpl, {
                    "data": data
                });
                $('.popup-concacts #concats').html(html);
                $(".popup-concacts #contactsType").val(type);
                $(".list-group-title").on("click",
                    function() {
                        var display = $(this).siblings('li').css("display");
                        $(this).siblings('li').toggle();
                    });
                // 选择联系人
                selectUser(func);
            }
        },
        error: function(data) {
            $.hideIndicator();
            $.toast("网络出错");
        }
    });
}
/**
 * 选择联系人
 */
function selectUser(fun) {
    $(".popup-concacts .select-user").on("click",
        function() {
            $(".popup-concacts #contactsInput").val("");
            $.closeModal('.popup-concacts');
            var id = $(this).attr("data-attr");
            var name = $(this).attr("data-name");
            if (fun && typeof fun === "function") {
                fun(id, name);
            }
        });
}

/**
 * 搜索联系人
 */
function searchContacts() {
    var type = $(".popup-concacts #contactsType").val();
    var val = $(".popup-concacts #contactsInput").val();
    $.showIndicator();
    $.ajax({
        type: "POST",
        url: "concacts",
        dataType: "json",
        data: {
            search: val,
            type: type
        },
        success: function(data) {
            $.hideIndicator();
            if (data.hasOwnProperty("rs") && data.rs == "Y") {
                var tpl = document.getElementById('popconcactsTpl').innerHTML;
                var html = template(tpl, {
                    "data": data
                });
                $('.popup-concacts #concats').html(html);
                $(".popup-concacts #contactsType").val(type);

                $(".list-group-title").on("click",
                    function() {
                        var display = $(this).siblings('li').css("display");
                        $(this).siblings('li').toggle();
                    });
                // 选择联系人
                selectUser(function(id) {
                    $.ajax({
                        url: "findUserById",
                        data: {
                            id: id,
                            type: type
                        },
                        type: "GET",
                        dataType: "json",
                        success: function(data) {
                            $.hideIndicator();
                            if (data.rs == 'Y') {
                                $("#ms_user_fk_user_id").text(data.user.real_name + "(" + data.user.phone + ")");
                                $("#ms_user_fk_user_id").attr("attr-data", id);
                            } else {
                                $.toast("系统出错");
                            }
                        },
                        error: function(data) {
                            $.hideIndicator();
                            $.toast("网络出错");
                        }
                    });

                });
            }
        }
    });
}
/* 将时间拆分成数组 */
function getTimeArr(time) {
    var d = new Date();
    if (time) {
        d = new Date(time);
    }
    var year = d.getFullYear() + "";
    var month = d.getMonth() + 1;
    month = month >= 10 ? month + "": "0" + month;
    var day = d.getDate();
    day = day >= 10 ? day + "": "0" + day;
    var hour = d.getHours() + "";
    var minute = d.getMinutes() + "";
    return [year, month, day, hour, minute];
}

/**
 * 格式化日期
 */
Date.prototype.format = function(fmt) {
    var o = {
        "M+": this.getMonth() + 1,
        // 月份
        "d+": this.getDate(),
        // 日
        "h+": this.getHours() + 10,
        // 小时
        "H+": this.getHours(),
        // 小时
        "m+": this.getMinutes(),
        // 分
        "s+": this.getSeconds(),
        // 秒
        "q+": Math.floor((this.getMonth() + 3) / 3),
        // 季度
        "S": this.getMilliseconds()
        // 毫秒
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}
/* 生成二维码 */
function getCode(obj) {
    var date = new Date();
    var times = date.getTime();
    var obj = JSON.parse(obj);
    obj["t"] = times;
    // obj["lat"] = "30.67";
    // obj["lot"] = "104.06";
    return JSON.stringify(obj);
}
/**
 * 获得当前登录用户的权限信息？？？
 *
 * @param id
 * @returns
 */
function getContact() {
    var role = "";
    $.ajax({
        url: "user",
        type: "POST",
        data: {
            type: "getContactById"
        },
        async: false,
        dataType: "json",
        success: function(data) {
            if (data.rs == "Y") {
                role = data.role;
            }
        },
        error: function(xhr, type) {
            $.hideIndicator();
            $.toast("您的网速不给力啊，再来一次吧");
        }
    });
    return role;
}
//会籍端打开发表心情的POPUP
function openInteractPopup(type) {
    $("#pics").val("");
    $("#type").val(type);
    $("#imagesView").html('<div class="col-25" onclick="chooicePhoto();" >' + '<img src="app/images/add2.png"' + '  class="publish-inter"  style="margin: 0; width: 100%;padding: 0;"></div>');
    $("#content").val("");
    $.popup(".popup-addInteract");
}
//显示可见范围
function whoIsShow() {
    var buttons1 = [{
        text: '可见范围',
        label: true
    },
        {
            text: '所有人',
            color: 'custom',
            onClick: function() {
                $("#whoIsShow").html('所有人');
            }
        },
        {
            text: '自己',
            color: 'custom',
            onClick: function() {
                $("#whoIsShow").html('自己');
            }
        }];
    var buttons2 = [{
        text: '取消',
        bg: 'custom'
    }];
    var groups = [buttons1, buttons2];
    $.actions(groups);
}
//选择图片
function chooicePhoto() {
    if (accessType == "w") {
        var images = {
            localIds: []
        };
        wx.ready(function() {
            wx.chooseImage({
                success: function(res) {
                    images.localIds = res.localIds;
                    $("#pics").val(res.localIds);
                    var length = images.localIds.length;
                    for (var i = 0; i < length; i++) {
                        $("#imagesView").prepend('<div class="col-25"><img src="' + images.localIds[i] + '" width="100%" height="88px" /></div>');
                    }
                }
            });
        });
    } else {
        var buttons1 = [{
            text: '选择图片',
            bold: true,
            color: 'danger',
            onClick: function() {
                try {
                    api.execScript({
                        name: 'root',
                        // 由于直接在index上使用openFrame，因此只需name root。
                        script: "uploadPhone('library');" // 这里的四个值分别在本地页面出发方法后由php传给js再传给本地的index。
                    });
                } catch(e) {}
            }
        },
            {
                text: '拍照',
                onClick: function() {
                    try {
                        api.execScript({
                            name: 'root',
                            // 由于直接在index上使用openFrame，因此只需name root。
                            script: "uploadPhone('camera');" // 这里的四个值分别在本地页面出发方法后由php传给js再传给本地的index。
                        });
                    } catch(e) {}
                }
            }];
        var buttons2 = [{
            text: '取消',
            bg: 'danger'
        }];
        var groups = [buttons1, buttons2];
        $.actions(groups);

    }
}
//发表说说 上传图片 -- app
function uploadPicSuccessByApp(url) {
    var ids = $("#pics").val();
    if (ids != "") {
        var xx = ids.split(",");
        if (xx.length > 9) {
            $.toast("最多只能上传9张图片哦");
            return;
        }
    }
    $.showIndicator();

    var baseUrl = 'http://oixty02vf.bkt.clouddn.com'; //七牛给你的测试域名，也可使用自己捆绑的域名youe.xxx.com
    var obj = api.require('qiniuUpfile');
    Math.random() * 700
    var num = Math.random() * 700 + 800;
    num = parseInt(num, 10);
    obj.upfile({
            file: url,
            name: num
        },
        function(ret, err) {
            if (ret.status) {
                if (ret.oper == "complete") {
                    $.hideIndicator();
                    url = baseUrl + "/" + ret.info.key;
                    $("#imagesView").prepend('<div class="col-25"><img src="' + url + '" width="100%" height="88px" /></div>');
                    ids += url + ",";
                    $("#pics").val(ids);

                } else if (ret.oper == "error") {
                    $.hideIndicator();
                    alert(JSON.stringify(ret));
                }

            } else {
                $.toast(JSON.stringify(err));
            }
        });

}
//发表说说
function sendInteract() {
    var content = $("#interact_content").val();
    var pics = $("#pics").val();
    var type = $("#type").val();
    var show = $("#whoIsShow").text();
    var localIds = pics.split(",");
    var serverId = "";
    if (content == "" && pics == "") {
        $.toast("说点什么吧");
        return
    }
    //微信
    if (accessType == "w") {
        if (pics != null && pics.length > 0) {
            wx.ready(function() {
                var i = 0;
                var length = localIds.length;
                var upload = function() {
                    wx.uploadImage({
                        localId: localIds[i],
                        success: function(res) {
                            serverId += res.serverId + ',';
                            // 如果还有照片，继续上传
                            i++;
                            if (i < length) {
                                upload();
                            } else {
                                $.showIndicator();
                                $.ajax({
                                    type: "POST",
                                    url: "yp-ws-app-uploadPhotoByUser",
                                    dataType: "json",
                                    data: {
                                        serverId: serverId,
                                        content: content,
                                        show: show,
                                        "t": "w",
                                        "type": type
                                    },
                                    success: function(data) {
                                        $.hideIndicator();
                                    },
                                    error: function(xhr, type) {
                                        $.hideIndicator();
                                        $.toast("您的网速不给力啊，再来一次吧");
                                    }
                                });
                            }
                        }
                    });
                };

                upload();

            });
        } else {
            $.showIndicator();
            $.ajax({
                type: "POST",
                url: "yp-ws-app-uploadPhotoByUser",
                dataType: "json",
                data: {
                    serverId: serverId,
                    content: content,
                    show: show,
                    "t": "w",
                    "type": type
                },
                success: function(data) {
                    $.hideIndicator();
                    getIneract();
                },
                error: function(xhr, type) {

                    $.hideIndicator();
                    $.toast("您的网速不给力啊，再来一次吧");
                }
            });
        }
    } else {
        $.showIndicator();
        $.ajax({
            type: "POST",
            url: "yp-ws-app-uploadPhotoByUser",
            dataType: "json",
            data: {
                serverId: pics,
                content: content,
                show: show,
                "t": "a",
                "type": type
            },
            success: function(data) {
                $.hideIndicator();
                getIneract();
            },
            error: function(xhr, type) {
                $.hideIndicator();
                $.toast("您的网速不给力啊，再来一次吧");
            }
        });

    }

    $.closeModal(".popup-addInteract");
}
// 点赞
function addGood(id) {

    $.showIndicator();
    $.ajax({
        type: "POST",
        url: "yp-ws-app-addGood",
        dataType: "json",
        data: {
            id: id
        },
        success: function(data) {
            $.hideIndicator();
            if (data.rs == "Y") {
                getIneract();
            } else {
                $.toast("您已经赞过了哦");
            }
        },
        error: function(xhr, type) {
            $.hideIndicator();
            $.toast("您的网速不给力啊，再来一次吧");
        }
    });
}
/*改变头像*/
function changeHeaderPic() {
    if (accessType == "w") {
        wx.chooseImage({
            count: 1,
            // 默认
            sizeType: ['compressed'],
            // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'],
            // 可以指定来源是相册还是相机，默认二者都有
            success: function(res) {
                var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                wx.uploadImage({
                    localId: '' + localIds,
                    // 需要上传的图片的本地ID，由chooseImage接口获得
                    isShowProgressTips: 1,
                    // 默认为1，显示进度提示
                    success: function(res) {
                        var serverId = res.serverId; // 返回图片的服务器端ID
                        $.ajax({
                            type: "POST",
                            url: "yp-ws-app-changeHeaderPic",
                            dataType: "json",
                            data: {
                                serverId: serverId
                            },
                            success: function(data) {
                                $.hideIndicator();
                                if (data.rs == "Y") {
                                    $.toast("上传成功");
                                    getMine();
                                } else if (data.rs == "N") {
                                    $.toast("出错了，请稍后重试");
                                } else {
                                    $.toast(data.rs);
                                }
                            },
                            error: function(xhr, type) {
                                $.hideIndicator();
                                $.toast("您的网速不给力啊，再来一次吧");
                            }
                        });
                    }
                });
            }
        });
    } else {
        var buttons1 = [{
            text: '选择图片',
            bold: true,
            color: 'danger',
            onClick: function() {
                try {
                    api.execScript({
                        name: 'root',
                        // 由于直接在index上使用openFrame，因此只需name root。
                        script: "uploadheadrPic('library');" // 这里的四个值分别在本地页面出发方法后由php传给js再传给本地的index。
                    });
                } catch(e) {}
            }
        },
            {
                text: '拍照',
                onClick: function() {
                    try {
                        api.execScript({
                            name: 'root',
                            // 由于直接在index上使用openFrame，因此只需name root。
                            script: "uploadheadrPic('camera');" // 这里的四个值分别在本地页面出发方法后由php传给js再传给本地的index。
                        });
                    } catch(e) {}
                }
            }];
        var buttons2 = [{
            text: '取消',
            bg: 'danger'
        }];
        var groups = [buttons1, buttons2];
        $.actions(groups);
    }
}
//app上传图片
function uploadheaderPicSuccessByApp(url) {
    $.showIndicator();
    var baseUrl = 'http://oixty02vf.bkt.clouddn.com'; //七牛给你的测试域名，也可使用自己捆绑的域名youe.xxx.com
    var obj = api.require('qiniuUpfile');
    Math.random() * 700
    var num = Math.random() * 700 + 800;
    num = parseInt(num, 10);
    obj.upfile({
            file: url,
            name: num
        },
        function(ret, err) {
            if (ret.status) {
                if (ret.oper == "complete") {
                    $.hideIndicator();
                    url = baseUrl + "/" + ret.info.key;
                    $.ajax({
                        type: "POST",
                        url: "yp-ws-app-changeHeaderPicByAPP",
                        dataType: "json",
                        data: {
                            picurl: url
                        },
                        success: function(data) {
                            $.hideIndicator();
                            if (data.rs == "Y") {
                                $.toast("上传成功");
                                getMine();
                            } else if (data.rs == "N") {
                                $.toast("出错了，请稍后重试");
                            } else {
                                $.toast(data.rs);
                            }
                        },
                        error: function(xhr, type) {
                            $.hideIndicator();
                            $.toast("您的网速不给力啊，再来一次吧");
                        }
                    });

                } else if (ret.oper == "error") {
                    $.hideIndicator();
                    $.toast("出错了，请稍后重试");
                    //	        	alert(JSON.stringify(ret));
                }

            } else {
                $.toast(JSON.stringify(err));
            }
        });
}

// 标题栏更多
function more(type) {
    var buttons1 = [{
        text: '扫码上课',
        color: 'custom',
        onClick: function() {
            scaner();
        }
    },
        {
            text: '发表动态',
            color: 'custom',
            onClick: function() {
                openInteractPopup("mem");
            }
        }];
    var buttons2 = [{
        text: '取消',
        bg: 'custom'
    }];
    var groups = [buttons1, buttons2];
    $.actions(groups);
}

function showPic(list) {
    $(".bar .bar-tab").css('display', 'none');
    var pic = list.split(",");
    var myPhotoBrowserPopup = $.photoBrowser({
        photos: pic,
        type: 'popup'
    });
    myPhotoBrowserPopup.open();
}
/**
 * 消息查询
 */
function recentMessage() {
    $(".main-header").hide();
    $(".main-content").css("top", "0");
    clearFilter();
    $.ajax({
        url: "yp-ws-app-messageRecent",
        type: "POST",
        dataType: "json",
        success: function(data) {
            if (data.rs == "Y") {
                var types = data.msg_type;
                var messages = data.msgs;
                if (messages && messages.length) {
                    var ml = template($("#messageListTpl").html(), {
                        list: messages,
                        types: types
                    });
                    $("#messageListDiv").html(ml);
                } else {
                    $("#messageListDiv").html("<div class='font9 none-info'>当前没有消息哦</div>");
                }
            } else {}
        }
    });
}

function showMessageDetail(li) {
    var l = $(li);
    var id = l.attr("data-sid");
    var title = l.attr("data-title");
    var content = l.attr("data-content");
    var detail_time = l.attr("data-send");
    var time = l.attr("data-time");
    var read = l.attr("data-read") == "true";

    if (!read) {
        readMessage(id, detail_time);
    }
    var detail = template($("#messageDetailTpl").html(), {
        title: title,
        content: content,
        time: time
    });
    $("#message-detail").html(detail);
    $.popup(".popup-message-detail");
    recentMessage();
}
/**
 * 消息读取
 * @param id
 * @param time
 */
function readMessage(id, time) {
    $.ajax({
        url: "yp-ws-app-messageRead",
        type: "POST",
        data: {
            msg_id: id,
            send_time: time
        },
        dataType: "json",
        success: function(data) {
            if (data.rs == "Y") {} else {
                $.toast(data.rs);
            }
        }
    });
}
/**支付*/
function pay(id, out_trade_no, subject, total_fee, pay_type) {
    var pre_ids = "";
    if (use_prefee) {
        $("input[name='prefee_ids']:checked").each(function() {
            var pid = $(this).attr("value");
            if (pid) pre_ids += pid + ",";
        });
    }
    $.showIndicator();
    if (pre_ids != "") {
        $.ajax({
            url: "pay-use-prefee",
            type: "POST",
            data: {
                flow_num: out_trade_no,
                pre_ids: pre_ids
            },
            async: false,
            dataType: "json",
            success: function(data) {
                $.hideIndicator();
                if (data.rs != "Y") {
                    $.toast(data.rs);
                    return false;
                }
            },
            error: function() {
                $.hideIndicator();
                $.toast("网络错误,提交抵扣券使用失败!");
                return false;
            }
        });
    }

    if (use_prefee) {
        total_fee = $("#order_moeny").text().replace("￥", "");
    }

    var payType = $("#payType").val();
    if ("alipay" == payType) {//支付宝支付
        $.hideIndicator();
        alipay(id, out_trade_no, subject, total_fee);
    } else if ("wechat" == payType) {//微信端---------微信支付
        if ("w" == accessType) {
            $.showIndicator();
            $.ajax({
                type: 'POST',
                url: "yp-ws-app-wechatPay",
                data: {
                    out_trade_no: out_trade_no,
                    subject: subject,
                    total_fee: total_fee
                },
                dataType: 'json',
                success: function(data) {
                    $.hideIndicator();
                    if (data.rs == "Y") {
                        var d = data.data;
                        // 支付成功 --- 查询订单
                        paycallpay(d.appid, d.timeStamp, d.nonceStr, d.packages, d.sign, out_trade_no, total_fee);
                    } else {
                        $.toast(data.rs);
                    }
                },
                error: function(xhr, type) {
                    $.hideIndicator();
                    $.toast("您的网速不给力啊，再来一次吧");
                }
            })
        } else if ("android" == accessType) {//APP端->微信支付
            $.showIndicator();
            $.ajax({
                type: 'POST',
                url: "yp-ws-app-wechatPaybyAPP",
                data: {
                    total_fee: total_fee
                },
                dataType: 'json',
                success: function(data) {
                    $.hideIndicator();
                    if (data.rs == "Y") {
                        var d = data.data;
                        var total_fee = d.total_fee;
                        // 配置微信相关参数
                        var wxPay = api.require('wxPay');
                        wxPay.config({
                                apiKey: d.appid,
                                mchId: d.mch_id,
                                partnerKey: d.partnerkey,
                                notifyUrl: d.notifyUrl
                            },
                            function(ret, err) {
                                if (ret.status) {
                                    // 配置成功
                                    wxPay.pay({
                                            description: subject,
                                            totalFee: total_fee,
                                            tradeNo: out_trade_no,
                                        },
                                        function(ret, err) {
                                            if (ret.status) {
                                                alert(ret.status);
                                                // 支付成功 --- 改变订单
                                                changeOrderSatus(out_trade_no, total_fee);
                                            } else {
                                                // 支付失败或者取消支付
                                                alert("支付失败");
                                            }
                                        });

                                } else {
                                    alert(err.code);
                                }
                            });

                    } else {
                        $.toast(data.rs);
                    }
                },
                error: function(xhr, type) {
                    $.hideIndicator();
                    $.toast("您的网速不给力啊，再来一次吧");
                }
            })
        } else {
            $.toast("暂未开放，敬请期待");
            $.hideIndicator();
            return;
        }
    } else if ("moneyBag" == payType) { // 余额支付
        if ("recharge" == pay_type) {
            $.hideIndicator();
            $.toast("账户充值请选择其他支付方式");
            return;
        }
        $.showIndicator();
        $.ajax({
            type: 'POST',
            url: "yp-ws-app-balancePay",
            data: {
                out_trade_no: out_trade_no,
                subject: subject,
                total_fee: total_fee,
            },
            dataType: 'json',
            success: function(data) {
                $.hideIndicator();
                if (data.rs == "Y") {
                    $.toast("支付成功");
                    $.closeModal(".popup-appPay");
                    getMineOrderList();
                } else {
                    $.toast(data.rs);
                }
            },
            error: function(xhr, type) {
                $.hideIndicator();
                $.toast("您的网速不给力啊，再来一次吧");
            }
        })
    } else {
        $.hideIndicator();
        $.toast("请选择支付方式");
    }
}
//支付宝支付 ---->未用
function alipay(id, out_trade_no, subject, total_fee) {
    if (!alipayParam) {
        $.toast("该健身房还未设置支付宝信息，暂不能使用支付宝支付");
        return;
    }
    if ("{}" == alipayParam) {
        $.toast("请重新登陆");
        return;
    }

    alipayParam = JSON.parse(alipayParam);
    var url = "app/alipayapi.jsp?WIDout_trade_no=" + out_trade_no + "&WIDsubject=" + subject + "&WIDtotal_fee=" + total_fee + "&partner=" + alipayParam.partner + "&private_key=" + alipayParam.private_key;
    $.showIndicator();
    $('.popup-article header .title').html("支付宝付款");

    var iframe = document.createElement("iframe");
    var randomnumber = Math.floor(Math.random() * 100000);
    if (url.indexOf("?") != -1) {
        url += "&" + randomnumber;
    } else {
        url += "?" + randomnumber;
    }

    var ok = false;
    iframe.src = url;
    if (iframe.attachEvent) {
        iframe.attachEvent("onload",
            function() {
                $('.popup-alipay iframe').width("100%");
                $('.popup-alipay iframe').height("100%");
                $.hideIndicator();
                ok = true;
                $.popup('.popup-article');
            });
    } else {
        iframe.onload = function() {
            $('.popup-alipay iframe').width("100%");
            $('.popup-alipay iframe').height("100%");
            $.hideIndicator();
            ok = true;
            $.popup('.popup-alipay');
        };
    }
    var bodyObj = document.getElementById("article_frame");
    var size = bodyObj.childNodes.length;
    if (size != null && size > 0) {
        for (var i = 0; i < size; i++) {
            bodyObj.removeChild(bodyObj.childNodes[0]);
        }
    }
    bodyObj.appendChild(iframe);
    setTimeout(function() {
            if (!ok) {
                size = bodyObj.childNodes.length;
                if (size != null && size > 0) {
                    for (var i = 0; i < size; i++) {
                        bodyObj.removeChild(bodyObj.childNodes[0]);
                    }
                }
                $.hideIndicator();
                $.toast("服务器繁忙，请稍后再试");
            }
        },
        5000);
    $.closeModal(".popup-appPay");
}
// 微信端--》 微信支付
function paycallpay(appId, timeStamp, nonceStr, packageValue, paySign, orderNo, total_fee) {
    WeixinJSBridge.invoke('getBrandWCPayRequest', {
            "appId": appId,
            "timeStamp": timeStamp,
            "nonceStr": nonceStr,
            "package": packageValue,
            "signType": "MD5",
            "paySign": paySign
        },
        function(res) {
            WeixinJSBridge.log(res.err_msg);
            if (res.err_msg == "get_brand_wcpay_request:ok") {
                // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回 ok，但并不保证它绝对可靠。
                // // 支付成功 --- 改变订单
                changeOrderSatus(orderNo, total_fee);
            } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
                $.toast("您取消了支付");
            } else {
                $.toast("支付失败，请稍后在试!");
            }
        })
}
//微信支付完成后 --- 根据订单号查询订单---》然后改变订单状态
function changeOrderSatus(trade_no, total_fee) {
    $.showIndicator();
    $.ajax({
        type: 'POST',
        url: "App_changeOrderByWecaht",
        data: {
            trade_no: trade_no,
            total_fee: total_fee
        },
        dataType: 'json',
        success: function(data) {
            $.hideIndicator();
            if (data.rs == "Y") {
                $.toast("支付成功！");
                getMineOrderList();
                $.closeModal(".popup-appPay");
                $.closeModal(".popup-buyCards");
                $.closeModal(".popup-buyClass");
                $.closeModal(".popup-sclassBuy");
            } else {
                $.toast(data.rs);
            }
        },
        error: function(xhr, type) {
            $.hideIndicator();
            $.toast("您的网速不给力啊，再来一次吧");
        }
    })
}
/*支付*/
/*扫码上课*/
function scaner() {
    if (accessType == "w") {//微信端扫码上课
        wx.ready(function() {
            wx.scanQRCode({
                needResult: 1,
                // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                scanType: ["qrCode", "barCode"],
                success: function(res) {
                    var result = res.resultStr;
                    if (typeof result == 'string') {
                        result = JSON.parse(result);
                    }
                    hadCalssByScan(result.id, result.private_id);
                }
            });
        });
    } else {//APP端扫码上课
        var FNScanner = api.require('FNScanner');
        FNScanner.openScanner({
                autorotation: false
            },
            function(ret, err) {
                if (ret) {
                    var result = ret;
                    if (typeof ret == 'string') {
                        result = JSON.parse(result);
                    }
                    var r = result.content;
                    if (typeof r == 'string') {
                        r = JSON.parse(r);
                    }
                    hadCalssByScan(r.id, r.private_id);
                } else {
                    $.toast(JSON.stringify(err));
                }
            });
    }
}
//扫码上课处理扫码出来的信息
function hadCalssByScan(id, private_id) {
    $.confirm('你确定现在就要上/下课吗？', function () {
        $.showIndicator();
        $.ajax({
            type: "POST",
            url: "yp-ws-app-hadCalssByScan",
            data: {
                id: id,
                private_id: private_id
            },
            dataType: "json",
            success: function(data) {
                $.hideIndicator();
                $.toast(data.rs);
            },
            error: function(xhr, type) {
                $.hideIndicator();
                $.toast("您的网速不给力啊，再来一次吧");
            }
        });
    });
}
/*扫码上课*/
//课程详情
function showClassDetial(name,time,detial,type){
    $("#classDetail_name").html(name);
    if(time == undefined){
        time = "--";
    }
    $("#classDetail_time").html(time);
    if(detial == undefined){
        detial = "无";
    }
    if(detial!="undefined"){
        $("#classDetail_detial").html(detial);
    }
    var src ="app/images/user/sclass_detail.jpg";
    if("g" == type){
        src ="app/images/user/gclass_detail.jpg";
    }
    $("#classDetail_background").attr("src",src);
    $.popup(".popup-classDetail");
}
//教练详情
function showCoachDetial(id){
    $.showIndicator();
    $.ajax({
        type: "POST",
        url: "yp-ws-app-getCoachDetial",
        data: {
            id: id
        },
        dataType: "json",
        success: function(data) {
            $.hideIndicator();
            if(data.rs == "Y"){
                $("#coachDetail_emp_name").html(data.emp.emp_name);
                var sex =data.emp.sex;
                if(sex == "male"){
                    sex="男";
                }else{
                    sex="女";
                }
                $("#coachDetail_sex").html(sex);
                $("#coachDetail_no").html(data.emp.emp_no);
                $("#coachDetail_phone").html(data.emp.phone);
                var pic2 = data.emp.pic2;
                if(pic2){
                    pic2 += "?imageView2/1/w/150/h/220";
                }
                $("#coachDetail_headPhoto").attr("src",pic2 || 'app/images/user/emp_default_head.jpg');
                var tpl = document.getElementById("coachDetail_customEvaluateTpl").innerHTML;
                content = template(tpl, {
                    comment:data.comment
                });
                $("#coachDetail_customEvaluate").html(content);
                $.popup(".popup-coachDetail");
            }else{
                $.toast(data);
            }
        },
        error: function(xhr, type) {
            $.hideIndicator();
            $.toast("您的网速不给力啊，再来一次吧");
        }
    });
}


Date.prototype.after = function(d) {
    return this.getTime() > d.getTime();
}
Date.prototype.before = function(d) {
    return this.getTime() < d.getTime();
}
Date.prototype.beforeToday = function() {
    var today_begin = new Date();
    today_begin.setMilliseconds(0);
    today_begin.setSeconds(0);
    today_begin.setMinutes(0);
    today_begin.setHours(0);
    return this.before(today_begin);
}

/**
 * 会员端成交信息查询
 */
function initTodo() {
    $(".main-header").html('<h1 class="title">我的待办</h1><a class="icon icon-filter pull-right" onclick="openSlider()"></a>');
    $(".main-header").show();
    $(".main-content").css("top", "2.2rem");
    $.showIndicator();
    var filter = getFilter();
    $.ajax({
        type : 'POST',
        url : 'yp-ws-app-deal',
        data : filter,
        dataType : 'json',
        success : function(data) {
            $.hideIndicator();
            if (data.rs == "Y") {
                var dealTpl = document.getElementById("dealTpl").innerHTML;
                content = template(dealTpl,{data:data.data
                });
                $("#dealDiv").html(content);

            } else {
                $.toast(data.rs);
            }
        },
        error : function() {
            $.toast("网络错误,获取待办列表失败!");
        }
    });
}

//打开过滤选择框
function openSlider(){
    $.openPanel("#filter_slider");
}

//获取过滤条件
function getFilter(){
    //过滤
    var sex = $(".sex-group").children(".active").text();
    var type = $(".type-group").children(".active").text();
    var time = $(".time-group").children(".active").text();
    var text = $(".filter-input").val();
    var obj = {sex: sex, type: type, time: time, text: text};
    return obj;
}

//过滤事件
function common_filter(){
    if($("#dealContent").hasClass("active")){
        //待办任务过滤
        initTodo();
    } else if("block" == $(".popup-common_pool").css("display")){
        //会籍公共池过滤
        openCommonPool();
    } else {
        //客户跟踪过滤
        $(".filter-tab").each(function(){
            var o = $(this).parents(".popup");
            if("block" == $(o).css("display")){
                eval($(o).children(".content").children(".filter-tab").children(".active").attr("onclick"));
            }
        });
    }
}

//确定过滤
function sureFilter(){
    var text = $(".filter-input").val();
    common_filter();
    $.closePanel("#filter_slider");
}
//重置过滤
function resetFilter(){
    clearFilter();
    $(".filter-tab").each(function(){
        var o =$(this).parents(".popup");
        if("block" == $(o).css("display")){
            eval($(o).children(".content").children(".filter-tab").children(".active").attr("onclick"));
        }
    });
}
//清空过滤条件
function clearFilter(){
    $(".filter-btns").children().removeClass("active");
    $(".filter-input").val("");
}